//
//  CInputBoxView.m
//  Learn
//
//  Created by Mac on 16/9/28.
//  Copyright © 2016年 展鸿科技. All rights reserved.
//

#import "CInputBoxView.h"
#define _UIKeyboardFrameEndUserInfoKey (&UIKeyboardFrameEndUserInfoKey != NULL ? UIKeyboardFrameEndUserInfoKey : @"UIKeyboardBoundsUserInfoKey")
@implementation CInputBoxButton

- (instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        [self setUserInteractionEnabled:YES];
        [self setTextAlignment:NSTextAlignmentCenter];
        [self setFont:[UIFont systemFontOfSize:13]];
        [self.layer setBorderWidth:1];
        [self.layer setCornerRadius:5];
    }
    return self;
}

@end

@interface spaceLable : UITextView

@end

@implementation spaceLable

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [[self nextResponder] touchesBegan:touches withEvent:event];
}

- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event{
    return false;
}

@end

@interface CInputBoxView()<UITextViewDelegate>
@property (nonatomic, strong) NSString *title;
@property (nonatomic, strong) UITextView *textView;
@property (nonatomic, strong) spaceLable *lblSpace;
@property (nonatomic, strong) UIView *boxView;
@property (nonatomic, strong) NSArray *btns;
@property (nonatomic, strong) NSString *place;
@property (nonatomic, strong) NSString *alertTitle;

@property (nonatomic, strong) void(^action)(CInputBoxView *, NSInteger);
@end

@implementation CInputBoxView


- (instancetype)init{
    self = [super initWithFrame:[UIScreen mainScreen].bounds];
    if (self) {
        
    }
    return self;
}

+(CInputBoxView *) showInputBox:(NSString *)title place:(NSString *)place show:(NSString*)alertTitle btns:(NSArray *)btns action:(void(^)(CInputBoxView *boxView, NSInteger index))action{
    CInputBoxView *boxView = [[CInputBoxView alloc] init];
    boxView.action = action;
    boxView.title = title;
    boxView.btns = btns;
    boxView.place = place;
    boxView.alertTitle=alertTitle;
    [boxView showBox];
    return boxView;
}

- (void) initView{
    [self setBackgroundColor:[UIColor clearColor]];
    UIView *bgView = [[UIView alloc] initWithFrame:self.bounds];
    [self addSubview:bgView];
    [bgView setBackgroundColor:[UIColor colorWithRed:0 green:0 blue:0 alpha:.6]];
    
    float width = self.frame.size.width * 2 / 3;
    float height = 120;
    _boxView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, width, height)];
    [_boxView setBackgroundColor:[UIColor whiteColor]];
    [self addSubview:_boxView];
    [_boxView setCenter:self.center];
    
    [_boxView.layer setCornerRadius:5];
    
    float y = 0;
    if (self.title) {
        UILabel *lblTitle = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, width, 30)];
        [_boxView addSubview:lblTitle];
        [lblTitle setFont:[UIFont systemFontOfSize:14]];
        [lblTitle setTextAlignment:NSTextAlignmentCenter];
        y = 30;
    }
    _textView = [[UITextView alloc] initWithFrame:CGRectMake(15, y + 10, width - 30, 60)];
    [_boxView addSubview:_textView];
    _textView.delegate=self;
    [_textView setBackgroundColor:[UIColor whiteColor]];
    
    if (self.place) {
        _lblSpace = [[spaceLable alloc] initWithFrame:_textView.frame];
        [_boxView addSubview:_lblSpace];
        [_lblSpace setEditable:NO];
        [_lblSpace setText:self.place];
        [_lblSpace setTextColor:C(@"b9b7b7")];
        [_lblSpace setBackgroundColor:[UIColor clearColor]];
    }
    
    
    y += 10 + _textView.frame.size.height + 10;
    
    UIView *btnView = [[UIView alloc] initWithFrame:CGRectMake(15, y + 10, width - 30, 30)];
    [_boxView addSubview:btnView];
    if (self.btns == nil || self.btns.count == 0) {
        self.btns = @[@"确定"];
    }
    
    int i = 0;
    float btnspace = 15;
    float btnwidth = (width - 30 - btnspace * (self.btns.count - 1)) / self.btns.count;
    for (id btn in self.btns) {
        if ([btn isKindOfClass:[NSString class]]) {
            CInputBoxButton *btnInput = [[CInputBoxButton alloc] initWithFrame:CGRectMake(i * (btnwidth + btnspace) , 0, btnwidth, btnView.frame.size.height)];
            [btnView addSubview:btnInput];
            btnInput.tag = i;
            [btnInput setText:btn];
            btnInput.layer.borderWidth =0.5;

            if (i == 0) {
                [btnInput setTextColor:Yellow];
                [[btnInput layer] setBorderColor:Yellow.CGColor];
            }else{
                [btnInput setTextColor:[UIColor colorFromHexString:@"969696"]];
                [[btnInput layer] setBorderColor:[UIColor colorFromHexString:@"969696"].CGColor];
            }

            [btnInput setUserInteractionEnabled:YES];
            __block int weaki = i;
            [btnInput bk_whenTapped:^{
                if (self.action) {
                    if(weaki ==0)
                    {
                        if ([_textView.text isEqualToString:@""]) {
                            [CClass showMessage:self.alertTitle];
                            return;
                        }else
                        {
                            [self hideBox];
                            
                        }
                        
                    }else
                    {
                        [self hideBox];
                        
                    }
                    self.action(self, weaki);
                }
            }];
        }else if([btn isKindOfClass:[CInputBoxButton class]]){
            [btnView addSubview:btn];
            [btn setFrame:CGRectMake(i * (btnwidth + btnspace) , 0, btnwidth, btnView.frame.size.height)];
            [btn setUserInteractionEnabled:YES];
            __block int weaki = i;
            [btn bk_whenTapped:^{
                if (self.action) {
                    if(weaki ==0)
                    {
                        if ([_textView.text isEqualToString:@""]) {
                            [CClass showMessage:self.alertTitle];
                            return;
                        }else
                        {
                            [self hideBox];
                            
                        }
                        
                    }else
                    {
                        [self hideBox];
                        
                    }
                    self.action(self, weaki);

                }
            }];

        }
        i ++;
    }
    y += 10 + 30 + 10;
    
    CGRect boxFrame = _boxView.frame;
    boxFrame.size.height = y;
    [_boxView setFrame:boxFrame];
}

- (id)inputData{
    return _textView.text;
}

- (void) btnAction:(UIGestureRecognizer *) button{
    NSInteger tag = button.view.tag;
    if (self.action) {
        if(tag ==0)
        {
            if ([_textView.text isEqualToString:@""]) {
                [CClass showMessage:self.alertTitle];
                return;
            }else
            {
                [self hideBox];

            }
            
        }else
        {
            [self hideBox];
 
        }
        self.action(self, tag);
    }
}

- (void) showBox{
    [self initView];
    
    [[[UIApplication sharedApplication] keyWindow] addSubview:self];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(ShowKeyboard:) name:UIKeyboardWillChangeFrameNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(HideKeyboard:) name:UIKeyboardWillHideNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(TextChange:) name:UITextViewTextDidChangeNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(TextEndEdit:) name:UITextViewTextDidEndEditingNotification object:nil];
    
}

- (void) hideBox{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [self removeFromSuperview];
}

- (void) ShowKeyboard:(NSNotification*)notification{
    CGRect keyboardRect = [self convertRect:[[[notification userInfo] objectForKey:_UIKeyboardFrameEndUserInfoKey] CGRectValue] fromView:nil];
    if (CGRectIsEmpty(keyboardRect)) {
        return;
    }
    if (keyboardRect.origin.y < CGRectGetMaxY(_boxView.frame)) {
        [UIView animateWithDuration:[[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue] animations:^{
            CGRect frame = _boxView.frame;
            frame.origin.y = keyboardRect.origin.y - CGRectGetHeight(frame);
            _boxView.frame = frame;
        } completion:^(BOOL finished) {
            
        }];
    }
}

- (void) HideKeyboard:(NSNotification*)notification{
    CGRect keyboardRect = [self convertRect:[[[notification userInfo] objectForKey:_UIKeyboardFrameEndUserInfoKey] CGRectValue] fromView:nil];
    if (CGRectIsEmpty(keyboardRect)) {
        return;
    }

    [UIView animateWithDuration:[[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue] animations:^{
        [_boxView setCenter:self.center];
    } completion:^(BOOL finished) {
        
    }];
}

- (void) TextChange:(NSNotification *) notification{
    if (self.place && self.textView.text.length > 0) {
        [_lblSpace setHidden:YES];
    }else if(self.place && self.textView.text.length == 0){
        [_lblSpace setHidden:NO];
    }
}

- (void) TextEndEdit:(NSNotification *) notification{
    if ([self.textView.text isEqualToString:self.place] || [self.textView.text isEqualToString:@""]) {
        self.textView.text = @"";
        [_lblSpace setHidden:NO];
    }
}

- (void)textViewDidChange:(UITextView *)textView{
    if (textView.markedTextRange == nil && textView.text.length > 20)  //加上 textView.markedTextRange == nil判断，当此属性为nil时，代表不在这种联想输入等待确定状态。
        
    {
        
        textView.text = [textView.text substringToIndex:20];
        
    }
}

@end
